package cn.com.callback

import cn.com.elite.EliteBean;
import cn.com.elite.Util
import cn.com.kh.CMUtil;
import cn.com.kh.KHUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 自动同步CM模板
 */

public class autoCMTemplateTask implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoCMTemplateTask.class);
    private static String log_Prefix = "自动同步CM模板-";

    private static String CM_ProductToken = "b4b49728-9eda-4f10-980e-da21ac4372b7";
    private static String CM_AccountID = "154d3c2e-472c-40df-a0e9-597647da4069";
    private static String CM_ChannelRequestId = "f47f65e1-52dd-4607-818a-67ec91c658ff";

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 处理头文件
        Map<String, String> headParams = new HashMap<String, String>();
        headParams.put("Content-Type", "application/json;charset=utf-8");
        headParams.put("X-CM-PRODUCTTOKEN", CM_ProductToken);

        // 同步WhatsApp模板类型
        doTemplates_Categories(eliteBean, jt, headParams);

        // 获取模板
        doTemplates(eliteBean, jt, headParams);

    }


    // 同步WhatsApp模板类型
    public static JSONObject doTemplates_Categories(EliteBean eliteBean, JdbcTemplate jt, headParams) {
        log.debug(log_Prefix + "模板类型字典同步");
        // 调用接口
        String CM_API_URL = "https://api.cm.com/channels/v1/accounts/{accountId}/whatsapp/{channelRequestId}/templates/categories".replace("{accountId}", CM_AccountID).replace("{channelRequestId}", CM_ChannelRequestId);
        String resultInfo = Util.doHttpGetUseHead(CM_API_URL, "UTF-8", 120000, 0, headParams);
        log.debug(log_Prefix + "模板类型字典同步API结果:" + resultInfo);

        // 处理返回信息
        JSONArray resultArr = JSONArray.fromObject(resultInfo);

        // 循环入库
        for (int i = 0; i < resultArr.size(); i++) {
            JSONObject tempJson = resultArr.getJSONObject(i);
            String ca_id = tempJson.getString("id");
            String ca_name = tempJson.getString("name");

            // 检查数据是否已经存在
            String selectExistSQL = '''Select Rec_Guid From Cm_Templates_Categories Where Ca_Id = ?''';
            List<Map<String, Object>> selectExistResult = jt.queryForList(selectExistSQL, ca_id);
            log.debug(log_Prefix + "模板类型检查结果:" + selectExistResult.toString());

            // 数据库操作
            if (selectExistResult.size() == 0) {
                String insertSQL = "Insert Into Cm_Templates_Categories (Rec_Guid, Ca_Id, Ca_Name, Ca_Desc, Sync_Time) Values (Uuid(), ?, ?, ?, Now())";
                int num = jt.update(insertSQL, ca_id, ca_name, "/");
                log.debug("新增数据(" + ca_name + ") 数量：" + num);
            } else {
                String updateSQL = "Update Cm_Templates_Categories Set Ca_Id = ?, Ca_Name = ?, Sync_Time = Now() Where Rec_Guid = ?";
                int num = jt.update(updateSQL, ca_id, ca_name, selectExistResult.get(0).get("Rec_Guid").toString());
                log.debug("更新数据(" + ca_name + ") 数量：" + num);
            }
        }
        log.debug(log_Prefix + "模板类型字典同步End");

    }


    // 同步WhatsApp模板
    public static JSONObject doTemplates(EliteBean eliteBean, JdbcTemplate jt, headParams) {
        log.debug(log_Prefix + "获取模板");
        // 调用接口
        String CM_API_URL = "https://api.cm.com/channels/v1/accounts/{accountId}/whatsapp/{channelRequestId}/templates".replace("{accountId}", CM_AccountID).replace("{channelRequestId}", CM_ChannelRequestId);
        String resultInfo = Util.doHttpGetUseHead(CM_API_URL, "UTF-8", 120000, 0, headParams);
        log.debug(log_Prefix + "获取模板API结果:" + resultInfo);

        // 处理返回信息
        JSONArray resultArr = JSONArray.fromObject(resultInfo);

        // 循环入库
        for (int i = 0; i < resultArr.size(); i++) {
            JSONObject tempJson = resultArr.getJSONObject(i);
            String Templates_ID = CMUtil.saveTemplat(eliteBean, jt, tempJson);

            // 获取模板详细信息-语言
            doTemplates_Detail(eliteBean, jt, headParams, Templates_ID);
        }
        log.debug(log_Prefix + "获取模板End");

    }


    // 同步WhatsApp模板详情
    public static JSONObject doTemplates_Detail(EliteBean eliteBean, JdbcTemplate jt, headParams, String Templates_ID) {
        log.debug(log_Prefix + "获取模板详情");
        // 调用接口
        String CM_API_URL = "https://api.cm.com/channels/v1/accounts/{accountId}/whatsapp/{channelRequestId}/templates".replace("{accountId}", CM_AccountID).replace("{channelRequestId}", CM_ChannelRequestId) + "/" + Templates_ID;
        String resultInfo = Util.doHttpGetUseHead(CM_API_URL, "UTF-8", 120000, 0, headParams);
        log.debug(log_Prefix + "获取模板详情API结果:" + resultInfo);

        int uoNum = jt.update("Update Cm_Templates Set templatjson = ? Where ID = ?", resultInfo, Templates_ID);
        log.debug(log_Prefix + "将完整详情Json对象更新到模板主表:" + uoNum);

        int delNum = jt.update("Update Cm_Templates_Languages Set Del_Flag = 1, Sync_Time = Now() Where Templates_ID = ?", Templates_ID);
        log.debug(log_Prefix + "将模板已经存在的语言信息记录更新更新为不可用:" + delNum);

        // 处理返回信息
        JSONObject resultJson = JSONObject.fromObject(resultInfo);
        JSONObject languagesJson = resultJson.getJSONObject("languages");

        // 循环入库
        for (Object str : languagesJson.keySet()) {
            String languageType = str;
            JSONObject tempJson = languagesJson.getJSONObject(languageType);
            CMUtil.saveTemplatLang(eliteBean, jt, tempJson, Templates_ID, languageType);
        }

        // 参数信息入库
        CMUtil.saveVariableLang(eliteBean, jt, resultJson, Templates_ID)
        log.debug(log_Prefix + "获取模板详情End");

    }

}
